﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;
namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_CategoryService: IPurchase_CategoryService
    {
        private List<Purchase_Category> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseCategoryCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_Category>(StaticConstraint.PurchaseCategoryCacheKey);
                if (List != null && List.Count > 0)
                    return List;

                List = DapperDbContext.Query<Purchase_Category>("select * from [Purchase_Category] where Status != @Status", new { Status = Status.delete }).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseCategoryCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseCategoryCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_Category>();
        }

        public (int count, List<Purchase_Category> list) GetList(string searchKey, int pageSize, int pageIndex)
        {
            int pageNum = (pageIndex - 1) * pageSize;
            var List = Init().Where(x => x.ParentId==Convert.ToInt32(searchKey)).OrderBy(x => x.Sorting).ThenBy(x => x.Name).ToList();
            var ParamList = List.Skip(pageNum).Take(pageSize).ToList();
            return (List.Count, ParamList);
        }
        public List<Purchase_Category> GetParentList(string searchKey)
        {
            var List = Init().Where(x => x.ParentId == 0).ToList();
            return List;
        }
        public int Save(Purchase_Category ent, UserCache user)
        {
            IDbModelService<Purchase_Category> db = new DbModelService<Purchase_Category>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (ent.Id == 0)
                    {
                        ent.Create(user);
                        var noteid = db.InsertOne(ent, conn, transaction);
                        ent.Id = noteid;

                        RedisBase.Hash_Set(StaticConstraint.PurchaseCategoryCacheKey, noteid, ent);
                        transaction.Commit();
                        return noteid;
                    }
                    else
                    {
                        ent.Modify(user);
                        db.UpdateById(ent, conn, transaction);
                        transaction.Commit();
                        if (ent != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseCategoryCacheKey, ent.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseCategoryCacheKey, ent.Id, ent);
                        }
                        return ent.Id;
                    }

                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                return -1;
            }
        }
        public int Del(List<int> Ids,UserCache user)
        {
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    string sql = "UPDATE [dbo].[Purchase_Category] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
                    int delcount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = user.UserId, LastUpdateTime = DateTime.Now, Id = Ids });
                    if(delcount>0)
                    {
                        foreach (var id in Ids)
                        {
                            RedisBase.Hash_Remove(StaticConstraint.PurchaseCategoryCacheKey, id.ToString());
                        }
                    }
                    return delcount;
                }
                    
            }
            catch (Exception ex)
            {

                return -1;
            }
           
        }
        public List<Purchase_Category> GetAllList()
        {
            return Init();
        }
    }
}
